<?php

namespace Create\Api;

/**
 * 创建控制器
 * @author Administrator
 */
class Controller
{

    private $name = ''; //控制器名称
    private $comment = ''; //控制器中文注释
    private $model = '';//存放到那个模块
    private $data = array();//字段信息数据

    public function __construct($name, $comment, $model, $data)
    {
        if (empty($name) || empty($model)) {
            exit('请传入控制器、模块名称');
        }
        $num = strpos($name, '_');
        $tmp = substr($name, $num + 1, 1);
        $this->name = ucfirst(str_replace('_' . $tmp, strtoupper($tmp), $name));
        $this->comment = $comment;
        $this->model = ucfirst($model);
        $this->data = $data;
    }

    public function create()
    {
        $str = $this->create_file_str();//产生字符串
        $path = APP_PATH . $this->model . '/Controller/' . $this->name . 'Controller.class.php';
        return File::create($path, $str);

    }

    /**
     * 创建文件字符串
     * @return string
     */
    private function create_file_str()
    {
        $fileUpStr = '';//文件上传代码
        $fileUpField = array();
        foreach ($this->data as $v) {
            if ($v['form'] == 'file') {
                array_push($fileUpField, $v['fields']);
                $fileUpStr = $this->create_file_up_str();
            }
        }
        $fileFieldStr = '';//是文件上传的字段取值代码
        $index = 0;
        foreach ($fileUpField as $v) {
            $fileFieldStr = "??post['{$v}']=??f_up[{$index}];";
            $index += 1;
        }
        //文件查询条件拼接
        $fileSearch = '';//查询文件
        $unlinkFile = '';//删除文件
        $where = '';
        foreach ($fileUpField as $v) {
            $where .= ',' . "'" . $v ."'";
        }
        $where = trim($where,',');
        if(!empty($where)){
            $fileSearch = "??fileNames=??{$this->name}->where(array('id'=>??data[??pk]))->field(array({$where}))->find();";
            $unlinkFile="if(??status){
                foreach(??fileNames as ??f){
                    unlink(??f);
                }
            }
            " ;
        }
        $time = date('Y-m-d H:i:s');
        $str = <<<PHP
<?php
                
/**
 * {$this->comment}控制器
 * TIME : {$time}
 */
 
namespace {$this->model}\Controller;
use Think\Controller;

class {$this->name}Controller extends Controller{

    //{$this->comment}首页
    public function index () {
        ??this->page = I('p',1) ;
        ??this->rows = I('rows',15) ;
        ??this->display();
    }
    
    //{$this->comment}编辑页面
    public function edit () {
        ??id = I('id',0,'intval') ;//接收用户ID
        if(!empty(??id)){
            ??this->{$this->name}Data = D('{$this->name}')->find(??id) ;
            ??this->edit = 1 ;
        }
        ??this->assign('page',I('page',1));
        ??this->assign('rows',I('rows',15));
        ??this->display();
    }

    //{$this->comment}删除页面
    public function del () {
        ??id = I('id',0,'intval') ;
        if(empty(??id)){
            ??this->error('请传入正确的参数');
        }
        ??action = D('{$this->name}')->delete(??id) ;
        if(??action===false){
            ??this->error('删除{$this->comment}失败');
        }else{
            ??this->success('删除{$this->comment}成功',U('index',array('p'=>I('page',1),'rows'=>I('rows',15)))) ;
        }
    }

    //{$this->comment}表单处理
    public function action () {
        {$fileUpStr}
        ??post = I('post.');
        {$fileFieldStr}
        ??{$this->name} = D('{$this->name}') ; //实例化模型
        //创建数据
        if(!??{$this->name}->create(??post)){
            ??this->error(??{$this->name}->getError());
        }
        ??data = ??{$this->name}->data() ;

        ??pk = ??{$this->name}->getPk() ; //获取主键
        ??action = '新增';
        //如果存在主键，表示为修改
        if( isset(??data[??pk]) && !empty(??data[??pk]) ){
            ??action = '修改';
            {$fileSearch}
            ??status = ??{$this->name}->save(??data);
            {$unlinkFile}
        }else{
            ??status = ??{$this->name}->add();
        }
        if(??status===false){
             ??this->error("{??action}{$this->comment}失败");
        }else{
            ??this->success("{??action}{$this->comment}成功",U('index')) ;
        }
    }
}
    
    
PHP;

        return str_replace('??', '$', $str);
    }

    //创建文件上传字符串
    public function create_file_up_str()
    {
        $str = '
        ??upload = new \Think\Upload();// 实例化上传类
        ??upload->rootPath = "./Uploads/"; // 设置附件上传根目录
        ??upload->savePath = "' . $this->name . '/"; // 设置附件上传（子）目录
        // 上传文件
        $info = $upload->upload();
        if (!??info) {// 上传错误提示错误信息
            ??this->error(??upload->getError());
        } else {// 上传成功
            ??f_up = array();
            foreach (??info as ??v) {
                ??f_up[] = "Uploads/" . ??v["savepath"] . ??v["savename"];
            }
        }
        ';
        return $str;
    }
}
